const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const url = require("url");
const serverObj = http.createServer((req,res)=>{
    const urlObj = url.parse(req.url);
    if(urlObj.pathname.includes("/api")){
        dataHandle(req, res);
    }else{
        staticHandle(req, res);
    }
})
serverObj.listen(3000,()=>{
    console.log("服务器开启成功,地址：http://localhost:3000")
})


// 数据处理路由的功能
function dataHandle(req,res){
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        programHandle(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end",()=>{
            const obj = qs.parse(str);
            programHandle(req, res, obj);
        })
    }
}
function programHandle(req, res, data){
    switch(data.type){
        case "getGoods":
            getGoods(req, res, data);
            break;
        case "getBanner":
            getBanner(req, res, data);
            break;
        case "login":
            login(req, res, data);
            break;
        case "register":
            register(req, res, data);
            break;
        case "getDetail":
            getDetail(req,res,data);
            break;
        default:
            error(req, res, data);
    }
}


function login(req, res, reqData) {
    fs.readFile("./database/user.json", "utf-8", (err, data) => {
        // 解析数据
        const userMsg = JSON.parse(data);
        // 遍历并查询用户信息
        let i = 0;
        const flag = userMsg.some((val, idx) => {
            i = idx;
            return val.username === reqData.username;
        })

        const obj = {};
        if (flag) {
            if (userMsg[i].password === reqData.password) {
                // 登录成功
                obj.code = 1;
                obj.title = "登录成功";
                obj.data = {username:reqData.username};
            } else {
                // 密码不对
                obj.code = 2;
                obj.title = "登录失败，密码不对";
                obj.data = "NOT DATE";
            }
        } else {
            // 没有找到用户名
            obj.code = 0;
            obj.title = "登录失败，用户名不存在";
            obj.data = "NOT DATE";
        }
        // 直接返回前端
        res.write(JSON.stringify(obj));
        res.end();
    })
}

// 注册功能（先读文件，再写文件）
function register(req, res, reqData){
    fs.readFile("./database/user.json","utf-8",(err,data)=>{
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        if(userMsg.some(val=>val.username === reqData.username)){
            obj.code = 0;
            obj.title = "注册失败，用户名重复";
            obj.data = "NOTDATA";
            res.write(JSON.stringify(obj));
            res.end();
        }else{
            // 没有重名，准备存储数据
            userMsg.push({
                username:reqData.username,
                password:reqData.password
            })
            fs.writeFile("./database/user.json", JSON.stringify(userMsg),err=>{
                const obj = {};
                // 存入数据库失败
                if(err){
                    obj.code = 2;
                    obj.title = "没有重名，但是写入数据库失败";
                    obj.data = {};
                }else{
                    // 存入成功，注册成功
                    obj.code = 1;
                    obj.title = "注册成功";
                    obj.data = "NOTDATA";

                }
                res.write(JSON.stringify(obj));
                res.end();
            })
        }
    })
}


function getDetail(req,res,reqData){
    fs.readFile("./database/goods.json", "utf-8", (err,data)=>{
        if(err){
            obj.code = 0;
            obj.title = "读取失败";
            obj.data = {};
            res.write(JSON.stringify(obj));
            res.end()
        }else{
            const goodsData = JSON.parse(data);
            let i=null;
            goodsData.some((val,idx)=>{
                i = idx;
                return val.proId === reqData.id
            })
            const obj = {};
            if(i === null){
                obj.code = 2;
                obj.title = "当前商品不存在";
                obj.data = {};
            }else{
                obj.code = 1;
                obj.title = "读取单个商品成功";
                obj.data = goodsData[i];
            }
            res.write(JSON.stringify(obj));
            res.end()
        }
    })
}

// 商品列表
function getGoods(req, res, data){
    fs.readFile("./database/goods.json",(err,data)=>{
        if(err){
            res.write("not data")
        }else{
            res.write(data)
        }
        res.end();
    })
}

//修改功能
function update(req, res, reqData) {
    console.log(reqData);
    // 1. 先读
    fs.readFile("./database/user.json", "utf-8", (err, msg) => {
        const msg1 = JSON.parse(msg);
        const msg2 = JSON.parse(msg);

        let i = 0;
        msg2.some((val, idx) => {
            i = idx;
            return val.username === reqData.username;
        })
        // 对查询到的要修改的数据进行修改
        msg2[i].password = reqData.password;

        // 4. 再将修改之后的数据，存回去
        fs.writeFile("./database/user.json", JSON.stringify(msg2), err => {
            const obj = {};
            if (err) {
                obj.code = 0;
                obj.title = "修改数据失败";
                obj.data = msg1;
            } else {
                obj.code = 1;
                obj.title = "修改数据成功";
                obj.data = msg2;
            }

            res.write(JSON.stringify(obj));

            res.end();
        })

    })
}

function error(req, res, data){
    res.write("Forbidden \n You don't  permission to access this resource.");
    res.end();
}




function staticHandle(req,res){
    const pn = url.parse(req.url).pathname
    fs.readFile("./www" + pn, (err,data)=>{
        if(err){
            res.write("Forbidden \n You don't have permission to access this resource.")
        }else{
            res.write(data);
        }
        res.end();
    })
}








function fileReq(req, res) {
    const urlObj = new URL("http://localhost:3000" + req.url);
    fs.readFile("./www" + urlObj.pathname, (err, data) => {
        if (err) {
            res.write("404");
        } else {
            res.write(data);
        }
        res.end();
    })
}